package cn.sise.edu.crm.shiro;

import cn.sise.edu.crm.domain.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * Created by chen on 2019/11/9.
 */
public class AjaxAuthenticationFilter extends FormAuthenticationFilter {

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        JsonResult result = new JsonResult("登录成功",true);
        try {
            response.getWriter().write(JSON.toJSON(result).toString());
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return false;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        String msg = "";
        if (e instanceof UnknownAccountException) {
            msg = "账号错误";
        } else if (e instanceof IncorrectCredentialsException) {
            msg = "密码错误";
        } else {
            msg = "未知错误";
        }
        e.printStackTrace();
        response.setContentType("application/json;charset=UTF-8");
        JsonResult result = new JsonResult(msg,false);
        try {
            response.getWriter().write(JSON.toJSON(result).toString());
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return false;
    }
}
